package a06_栈与队列;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <p>
 * a03_用队列实现栈复习2
 * </p>
 *
 * @author flyduck
 * @since 2024/12/25
 */
public class a03_用队列实现栈复习2 {
    public static void main(String[] args) {
        MyStack3 myStack3 = new MyStack3();
        myStack3.push(1);
        myStack3.push(2);
        myStack3.push(3);
        System.out.println(myStack3.top());
        System.out.println(myStack3.pop());
    }
}


class MyStack3{
    //1,2,3
    //

    Queue<Integer> queue1;
    Queue<Integer> queue2;

    public MyStack3() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        if(queue1.isEmpty() && queue2.isEmpty()){
            queue1.add(x);
        }else if(!queue1.isEmpty()){
            queue1.add(x);
        }else if(!queue2.isEmpty()){
            queue2.add(x);
        }
    }

    public int pop() {
        Queue<Integer> popQueue = !queue1.isEmpty() ? queue1 : queue2;
        Queue<Integer> pushQueue = queue1.isEmpty() ? queue1 : queue2;
        while (popQueue.size() > 1) {
            pushQueue.add(popQueue.poll());
        }
        return popQueue.poll();
    }

    public int top() {
        Queue<Integer> popQueue = !queue1.isEmpty() ? queue1 : queue2;
        Queue<Integer> pushQueue = queue1.isEmpty() ? queue1 : queue2;
        while (popQueue.size() > 1) {
            pushQueue.add(popQueue.poll());
        }
        Integer peek = popQueue.peek();
        pushQueue.add(popQueue.poll());
        return peek;
    }

    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}
